<template>
  <div class="wx-renyuan-container">
    <!-- 原有头部导航 -->
    <el-header class="header">
      <div class="logo">
        <img src="@/logo/1.png" alt="系统logo" class="logo-img">
      </div>
      <div class="top-nav">
        <router-link class="nav-item" :class="{ 'active': $route.path === '/wx-renyuan/repair-tasks' }"
          to="/wx-renyuan/repair-tasks">报修任务</router-link>
        <router-link class="nav-item" :class="{ 'active': $route.path === '/wx-renyuan/fault-progress' }"
          to="/wx-renyuan/fault-progress">历史维修订单</router-link>
        <router-link class="nav-item" :class="{ 'active': $route.path === '/wx-renyuan/robot-logs' }"
          to="/wx-renyuan/robot-logs">机器人日志</router-link>
        <router-link class="nav-item" :class="{ 'active': $route.path === '/wx-renyuan/maintenance-plan' }"
          to="/wx-renyuan/maintenance-plan">查看维护计划</router-link>
        <router-link class="nav-item" :class="{ 'active': $route.path === '/wx-renyuan/maintenance-logs' }"
          to="/wx-renyuan/maintenance-logs">维护日志</router-link>
      </div>
      <div class="header-actions">
        <router-link to="/wx-renyuan"><el-icon class="icon">
            <User />
          </el-icon></router-link>
        <router-link to="/phone"><el-icon class="icon">
            <Phone />
          </el-icon></router-link>
        <!-- 删除铃铛图标 -->
        <router-link to="/login"><el-icon class="icon">
            <CircleClose />
          </el-icon></router-link>
      </div>
    </el-header>

    <!-- 新增设备管理统计内容 -->
    <el-main class="main-content">
      <div v-show="$route.path === '/wx-renyuan'" class="stats-container">
        <el-row :gutter="20">
          <!-- 维修任务总数 -->
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ repairTasksCount }}</div>
                <div class="stat-label">维修任务总数</div>
                <div class="stat-icon purple-icon"><i class="el-icon-document"></i></div>
              </div>
            </el-card>
          </el-col>

          <!-- 维护计划总数 -->
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ maintenancePlansCount }}</div>
                <div class="stat-label">维护计划总数</div>
                <div class="stat-icon blue-icon"><i class="el-icon-schedule"></i></div>
              </div>
            </el-card>
          </el-col>

          <!-- 历史维修任务总数 -->
          <el-col :span="8">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ completedRepairsCount }}</div>
                <div class="stat-label">历史维修任务总数</div>
                <div class="stat-icon green-icon"><i class="el-icon-check"></i></div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 添加ECharts图表容器 -->
        <div class="chart-container">
          <el-card>
            <div id="repairStatusChart" class="chart-content"></div>
          </el-card>
        </div>
      </div>

      <!-- 原有路由视图 -->
      <router-view class="router-content"></router-view>
    </el-main>
  </div>
</template>

<script>
import { User, Phone, CircleClose } from '@element-plus/icons-vue';
import { ElHeader, ElMain, ElRow, ElCol, ElCard } from 'element-plus';
import { useRoute } from 'vue-router';
import * as echarts from 'echarts';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';

export default {
  name: 'WxRenyuanHome',
  components: {
    ElHeader, ElMain, ElRow, ElCol, ElCard,
    User, Phone, CircleClose
  },
  data() {
    return {
      repairStatusChart: null,
      repairTasksCount: 0,
      maintenancePlansCount: 0,
      completedRepairsCount: 0,
      loading: false
    };
  },
  setup() {
    const route = useRoute();
    return { route };
  },
  methods: {
    async fetchStatistics() {
      this.loading = true;
      try {
        // 获取维修任务总数
        const repairRes = await request.get('/users/getMyRepair');
        this.repairTasksCount = repairRes.code === 200 ? repairRes.data.length : 0;

        // 获取维护计划总数
        const maintenanceRes = await request.get('/users/getMyMaintenanceSchedules');
        this.maintenancePlansCount = maintenanceRes.code === 200 ? maintenanceRes.data.length : 0;

        // 获取历史维修任务总数
        const historyRes = await request.get('/users/getMyCompletedRepair');
        this.completedRepairsCount = historyRes.code === 200 ? historyRes.data.length : 0;

        // 更新图表
        this.initChart();
      } catch (error) {
        console.error('获取统计数据失败:', error);
        ElMessage.error('获取统计数据失败');
      } finally {
        this.loading = false;
      }
    },
    initChart() {
      const chartDom = document.getElementById('repairStatusChart');
      if (!chartDom) return;

      // 强制设置容器尺寸
      chartDom.style.width = '100%';
      chartDom.style.height = '400px';

      // 销毁已有实例
      if (this.repairStatusChart) {
        this.repairStatusChart.dispose();
      }

      // 初始化图表时指定尺寸
      this.repairStatusChart = echarts.init(chartDom, null, {
        width: 'auto',
        height: 400 // 显式指定高度
      });

      const option = {
        title: { text: '任务统计分布' },
        tooltip: { trigger: 'item' },
        series: [{
          name: '任务类型',
          type: 'pie',
          radius: '60%',
          data: [
            { value: this.repairTasksCount, name: '维修任务' },
            { value: this.maintenancePlansCount, name: '维护计划' },
            { value: this.completedRepairsCount, name: '历史维修' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };

      this.repairStatusChart.setOption(option);
      this.repairStatusChart.resize();
    },
    // 添加路由变化时的尺寸调整
    handleRouteChange() {
      this.$nextTick(() => {
        if (this.repairStatusChart) {
          this.repairStatusChart.resize();
        }
      });
    }
  },
  mounted() {
    this.fetchStatistics();
    window.addEventListener('resize', this.handleResize);
    this.$router.afterEach(this.handleRouteChange);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
    this.$router.afterEach(() => { }); // 移除路由监听
    if (this.repairStatusChart) {
      this.repairStatusChart.dispose();
    }
  }
}
</script>

<style scoped>
/* 容器样式 */
.wx-renyuan-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶端导航栏样式 */
.header {
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #e9e9e9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-bottom: none;
}

/* Logo样式 */
.logo {
  display: flex;
  align-items: center;
  background-color: transparent;
}

.logo-img {
  height: 40px;
  width: auto;
  object-fit: contain;
}

/* 导航菜单 */
.top-nav {
  display: flex;
  flex: 1;
  margin: 0 20px;
  height: 100%;
  background-color: transparent;
  position: relative;
  z-index: 10;
}

/* 导航菜单项 */
.nav-item {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #333 !important;
  font-size: 14px;
  font-weight: 500;
  padding: 0 10px;
  box-sizing: border-box;
  position: relative;
  z-index: 11;
  text-decoration: none;
}

.nav-item.active {
  background-color: #dcdcdc;
}

.nav-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: #409EFF;
}

/* 操作图标区域 */
.header-actions {
  display: flex;
  gap: 20px;
  /* 平均分配空间 */
}

.icon {
  font-size: 20px;
  cursor: pointer;
  color: #333;
  background-color: transparent;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

/* 统计卡片样式 */
.stats-container {
  padding: 20px;
}

.stat-card {
  height: 150px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
}

.stat-content {
  position: relative;
  padding: 15px;
  height: 100%;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  color: #606266;
  margin-bottom: 5px;
}

.stat-icon {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.blue-icon {
  background-color: #409eff;
}

.purple-icon {
  background-color: #722ed1;
}

.green-icon {
  background-color: #52c41a;
}

.chart-container {
  width: 100% !important;
  height: 400px !important;
  /* 设置固定高度 */
  margin-top: 20px;
  min-width: 300px;
  /* 添加最小宽度保障 */
}

.chart-content {
  width: 100% !important;
  height: 100% !important;
  /* 强制继承容器高度 */
  min-height: 400px !important;
  display: block !important;
}

/* 修复可能的父容器限制 */
.main-content {
  padding: 20px;
  overflow: visible !important;
  /* 确保内容不被裁剪 */
}

.stats-container {
  padding: 20px;
  box-sizing: border-box;
  /* 确保内边距不影响尺寸计算 */
}

/* 子页面内容边距调整 */
.router-content {
  margin-top: 20px;
}

/* 确保子页面全屏显示时无额外间距 */
:deep(.router-content-fullscreen) {
  margin-top: 0;
}
</style>

/* 路由内容区域 */